<template>
  <el-dialog
    v-model="dialogVisible"
    title="📦 选择商品"
    width="860px"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    @closed="onDialogClosed"
  >
    <!-- 搜索区域 -->
    <div class="search-containe r mb-10 flex justify-between items-center">
      <el-input
        v-model="searchKeyword"
        placeholder="🔍 搜索商品名称或SKU"
        clearable
        style="width: 300px"
        @input="debouncedSearch"
      />
      <el-tag type="info" size="large" class="ml-10">共 {{ total }} 个商品</el-tag>
    </div>

    <!-- 表格 -->
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="goodsList"
      style="width: 100%"
      :row-key="(row) => row.id"
      border
      stripe
      height="400"
      :header-cell-style="{ background: '#f5f7fa', fontWeight: '600' }"
      :cell-style="{ fontSize: '14px' }"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column prop="name" label="商品名称" min-width="180">
        <template #default="{ row }">
          <RowGoodsSlots :row="row" name="product" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品图形" min-width="180">
        <template #default="{ row }">
          <RowGoodsSlots :row="row" name="productImage" />
        </template>
      </el-table-column>
      <el-table-column prop="sku" label="商品规格" min-width="130">
        <template #default="{ row }">
          <RowGoodsSlots :row="row" name="productUnitNum" />
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" min-width="100" align="center">
        <template #default="{ row }">
          <RowGoodsSlots :row="row" name="price" />
        </template>
      </el-table-column>
      <el-table-column prop="isFixed" label="是否固定" min-width="90" align="center">
        <template #default="{ row }">
          <el-tag :type="row.isFixed ? 'success' : 'danger'" size="small">{{
            row.isFixed ? '是' : '否'
          }}</el-tag>
        </template>
      </el-table-column>

      <!-- 操作：选择 -->
      <el-table-column label="操作" min-width="90" align="center">
        <template #default="{ row }">
          <el-button type="primary" link text size="small" @click="handleSelect(row)"
            >选择</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container mt-4 flex justify-end">
      <el-pagination
        :current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
        background
        @current-change="handlePageChange"
      />
    </div>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue';
import { listProduct } from '../../api/goods';
import { cloneDeep } from 'lodash';

const emit = defineEmits(['ok']);

// ------------------ 数据与状态 ------------------
const dialogVisible = ref(false);
const loading = ref(false);
const goodsList = ref([]);
const total = ref(0);

// 分页参数
const pageNum = ref(1);
const pageSize = ref(10); // 每页10条，可调整为15或20

// 搜索关键词
const searchKeyword = ref('');
const searchBuffer = ref(''); // 缓存搜索词用于分页查询

// 选中商品
const selectedGoods = ref([]);
const tableRef = ref(null);

// ------------------ 获取数据 ------------------
const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      externalType: 1,
      type: 1
    };

    // 如果有搜索关键词，加入过滤
    if (searchBuffer.value) {
      params.keyword = searchBuffer.value;
    }

    const res = await listProduct(params);
    // 假设接口返回格式：{ data: { list, total } }
    const data = res;
    goodsList.value = data?.rows || [];
    total.value = parseInt(data?.total || 0);
  } catch (error) {
    console.error('获取商品列表失败:', error);
    goodsList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// ------------------ 搜索防抖 ------------------
let searchTimer = null;
const debouncedSearch = () => {
  if (searchTimer) clearTimeout(searchTimer);
  searchTimer = setTimeout(() => {
    searchBuffer.value = searchKeyword.value;
    pageNum.value = 1; // 重置页码
    fetchData();
  }, 500); // 500ms 防抖
};

// ------------------ 分页事件 ------------------
const handlePageChange = (page) => {
  pageNum.value = page;
  fetchData();
};

// ------------------ 确认与关闭 ------------------
const handleSelect = (row) => {
  emit('ok', cloneDeep(row), cacheIndex.value);
  handleClose();
};

const onDialogClosed = () => {
  // 重置所有状态
  searchKeyword.value = '';
  searchBuffer.value = '';
  pageNum.value = 1;
  selectedGoods.value = [];
  goodsList.value = [];
  total.value = 0;
  if (tableRef.value) {
    tableRef.value.clearSelection();
  }
};

const handleClose = () => {
  dialogVisible.value = false;
};

// ------------------ 暴露方法供父组件调用 -----------------
const cacheIndex = ref(null);
const show = (index) => {
  dialogVisible.value = true;
  cacheIndex.value = index;
  fetchData();
};

defineExpose({
  show
});
</script>

<style scoped>
.search-container {
  padding: 0 2px;
}

.dialog-footer {
  font-size: 14px;
}

.el-avatar {
  border-radius: 4px;
}

/* 响应式 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 95% !important;
  }
}
</style>
